package elasticsearch.util;

import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * 搜索
 * @author jiangbang
 * @date 2017/7/27
 */
public class EsSearchUtil {

    private static final String index = "index1";
    private static final String index2 = "index2";
    private static final String type = "type1";
    private static final String type2 = "type2";

    /**
     * 范围查询+term查询
     * @param client
     */
    public static void range (TransportClient client) {
//        //查询所有
//        SearchResponse response = client.prepareSearch().get();

        //通过条件筛选  年龄在12-18岁，
        SearchResponse response = client.prepareSearch(index) //可以多index
                .setTypes(type) //可以多type
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(termQuery("sex", "男"))                 // Query
                .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter
                .setFrom(0).setSize(60).setExplain(true)
                .get();

        SearchHit[] searchHits = response.getHits().getHits();
        for(SearchHit searchHit:searchHits){
            System.out.println(searchHit.getSource());
        }

    }

    /**
     * scrolls
     * @param client
     */
    public static void scroll (TransportClient client) {
        QueryBuilder qb = termQuery("sex", "男");

        SearchResponse scrollResp = client.prepareSearch(index)
                .addSort("age", SortOrder.ASC) //按年龄排序
                .setScroll(new TimeValue(3))
                .setQuery(qb)
                .setSize(3).get(); //最多返回100条数据
        do {
            for (SearchHit hit : scrollResp.getHits().getHits()) {
                System.out.println(hit.getSource());
            }

            scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
        } while(scrollResp.getHits().getHits().length != 0);
    }

    /**
     * 多搜素
     * @param client
     */
    public static void multiSearch (TransportClient client) {
        SearchRequestBuilder srb1 = client
                .prepareSearch().setQuery(QueryBuilders.queryStringQuery("elasticsearch")).setSize(1);
        SearchRequestBuilder srb2 = client
                .prepareSearch().setQuery(QueryBuilders.matchQuery("sex", "男")).setSize(1);

        MultiSearchResponse sr = client.prepareMultiSearch()
                .add(srb1)
                .add(srb2)
                .get();

        long nbHits = 0;
        for (MultiSearchResponse.Item item : sr.getResponses()) {
            SearchResponse response = item.getResponse();
            nbHits += response.getHits().getTotalHits();
        }
    }

    /**
     * 聚合搜索
     * @param client
     */
    public static void aggregations (TransportClient client) {
        SearchResponse sr = client.prepareSearch()
                .setQuery(QueryBuilders.matchAllQuery())
                .addAggregation(
                        AggregationBuilders.terms("agg1").field("field")
                )
                .addAggregation(
                        AggregationBuilders.dateHistogram("agg2")
                                .field("birth")
                                .dateHistogramInterval(DateHistogramInterval.YEAR)
                )
                .get();
        Terms agg1 = sr.getAggregations().get("agg1");
    }

    public static void terminateAfter (TransportClient client) {
        SearchResponse sr = client.prepareSearch()
                .setQuery(QueryBuilders.matchAllQuery())
                .addAggregation(
                        AggregationBuilders.terms("agg1").field("field")
                )
                .addAggregation(
                        AggregationBuilders.dateHistogram("agg2")
                                .field("birth")
                                .dateHistogramInterval(DateHistogramInterval.YEAR)
                )
                .get();
        Terms agg1 = sr.getAggregations().get("agg1");
    }
}
